package com.ruoyi.common.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.FileNotFoundException;

/**
 * office文件转pdf工具类
 */
public class Office2PDFUtils {
    private static final Logger log = LoggerFactory.getLogger(Office2PDFUtils.class);


    /**
     * 将office文档转成pdf文件
     * @param sourcePath
     * @param targetPath
     * @throws Exception
     */
    public static boolean word2pdf(String sourcePath, String targetPath) throws Exception {
        if (!new File(sourcePath).exists()) {
            throw new FileNotFoundException();
        }
        String command = String.format("soffice --convert-to pdf:writer_pdf_Export %s --outdir %s", sourcePath, targetPath);
        boolean flag = executeCommand(command);
        log.info("word2pdf: convert pdf complete. flag="+flag);
        return flag;
    }

    /**
     * 执行libreoffice的转换命令
     * @param command
     * @return
     */
    public static boolean executeCommand(String command){
        try {
            long start = System.currentTimeMillis();
            Process process = Runtime.getRuntime().exec(command);
            // 返回值是子线程执行完毕的返回值,返回0表示正常结束
            int exitStatus = process.waitFor();
            log.info("executeCommand: convert pdf exitStatus= " + exitStatus);

            // 销毁子进程
            process.destroy();
            long end = System.currentTimeMillis();
            log.info("executeCommand: convert pdf cost time " + (end - start) + "ms");
            return exitStatus == 0;
        }catch (Exception e){
            log.error("executeCommand: runtime exec error", e);
        }
        return false;
    }

}

